package com.ddwl.user.service;

import com.ddwl.common.util.BeanConverUtils;
import com.ddwl.common.util.DistanceUtil;
import com.ddwl.schema.bo.user.TrackBo;
import com.ddwl.schema.model.Location;
import com.ddwl.schema.vo.user.TrackVo;
import com.ddwl.user.model.Track;
import com.ddwl.user.repository.DeviceRepository;
import com.ddwl.user.repository.TrackRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Fu Zhaohui
 * @version 1.0.0
 * @date 2021/6/1 10:11
 */
@Service
@RequiredArgsConstructor
public class TrackService {

    private final TrackRepository trackRepository;
    private final DeviceRepository deviceRepository;

    public void upload(TrackBo bo) {
        Map<String, Location> latestTracks = trackRepository.findLatestByMacAndUserId(bo.getMacs(), bo.getOperator());
        List<String> macs = latestTracks.keySet().stream().filter(key -> DistanceUtil.distance(latestTracks.get(key), bo.getLoc()) <= 1).collect(Collectors.toList());
        List<Track> tracks = bo.getMacs().stream().filter(mac -> !macs.contains(mac)).map(mac -> {
            Track track = new Track();
            track.setMac(mac);
            track.setUserId(bo.getOperator());
            track.setLoc(bo.getLoc());
            track.setWifi(bo.getWifi());
            track.setGmtCreated(Instant.now());
            return track;
        }).collect(Collectors.toList());
        if (!tracks.isEmpty()) {
            trackRepository.insert(tracks);
        }
        deviceRepository.batchUpdateLoc(bo.getMacs(), bo.getLoc());
    }

    public List<TrackVo> device(String mac) {
        Track track = new Track();
        track.setMac(mac);
        Example<Track> example = Example.of(track, ExampleMatcher.matching());
        return trackRepository.findAll(example, PageRequest.of(0, 100, Sort.by(Sort.Direction.DESC, "gmtCreated"))).stream()
                .map(item -> BeanConverUtils.convertBean(item, TrackVo.class)).collect(Collectors.toList());
    }
}
